package cn.itcast.servlet;

import cn.itcast.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

/**
 * @param
 * @return
 */
@WebServlet("/DemoServlet01/*")
public class DemoServlet01 extends BeanServlet {
    private void findAll(HttpServletRequest request,HttpServletResponse response){
        System.out.println("findAll");
    }
    private void addStudentServlet(HttpServletRequest req,HttpServletResponse resp){

        try {
            //防止乱码
            req.setCharacterEncoding("utf-8");
            //获取表单的参数，封装为学生对象
            String name = req.getParameter("username");
            String age = req.getParameter("age");
            String score = req.getParameter("score");
            Student student = new Student(name, Integer.parseInt(age), Integer.parseInt(score));
            //写进文件，获取输出流,先防止乱码
            resp.setContentType("text/html;charset=utf-8");
            //获取输出流，指定写出的文件位置
            BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\stu.txt",true));
            bw.write(student.getName()+","+student.getAge()+","+student.getScore());
            bw.newLine();
            bw.close();
            //定时刷新给浏览器
            resp.getWriter().write("添加成功，2秒后跳转到首页");
            resp.setHeader("Refresh","2;URL=/day01/index.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void findAllStudentServlet(HttpServletRequest req,HttpServletResponse resp){
        //从系统文件中获取学生信息
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("d:\\stu.txt"));
            //创建集合，将封装了学生信息的对象存进去
            ArrayList<Student> list = new ArrayList<>();
            //获取字符输入流中的数据
            String len;
            while ((len=br.readLine())!=null){
                //注意！！！创建对象的操作要在循环里完成，保证每一段读出来切割后封装的都是新的对象，不然会一致重新赋值这样
                Student student = new Student();
                String[] split = len.split(",");
                student.setName(split[0]);
                student.setAge(Integer.parseInt(split[1]));
                student.setScore(Integer.parseInt(split[2]));
                list.add(student);
            }
            System.out.println(list.size());
            //赋值完事之后，向页面写出
            resp.setContentType("text/html;charset=utf-8");
            for (Student student1 : list) {
                resp.getWriter().write(student1.getName()+","+student1.getAge()+","+student1.getScore());
                resp.getWriter().write("<br>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
